package stdio.costa.imoca.api;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import stdio.costa.imoca.model.DocumentTemplate;
import stdio.costa.imoca.model.PostcardTemplate;
import stdio.costa.imoca.utils.IOUtils;

import com.sun.jersey.multipart.FormDataParam;

@Path("/template")
@Component
@Scope("request")
public class PostcardTemplateApi {

	@PersistenceContext
	private EntityManager entityManager;

	@Path("/doc")
	@POST
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces({ "application/json", "application/xml" })
	@Transactional
	public DocumentTemplate createDocumentTemplate(@FormDataParam("doc") InputStream in, @FormDataParam("name") String name,
			@FormDataParam("description") String description) throws IOException {
		byte[] doc = IOUtils.read(in);
		DocumentTemplate template = new DocumentTemplate(name, description, doc);
		entityManager.persist(template);
		return template;
	}

	@Path("/doc/{uuid}")
	@GET
	@Produces({ "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/pdf" })
	public Response getDocumentTemplate(@PathParam("uuid") String uuid) {
		DocumentTemplate doc = entityManager.find(DocumentTemplate.class, uuid);
		return Response.ok(new ByteArrayInputStream(doc.getData())).build();
	}

	@POST
	@Produces({ "application/json", "application/xml" })
	@Transactional
	public PostcardTemplate createPostcardTemplate(@FormParam("front") String frontUuid, @FormParam("back") String backUuid) {
		DocumentTemplate front = entityManager.find(DocumentTemplate.class, frontUuid);
		DocumentTemplate back = entityManager.find(DocumentTemplate.class, backUuid);
		PostcardTemplate template = new PostcardTemplate(front, back);
		entityManager.persist(template);
		return template;
	}

	@Path("/{uuid}")
	@GET
	@Produces({ "application/json", "application/xml" })
	public PostcardTemplate getPostcardTemplate(@PathParam("uuid") String uuid) {
		return entityManager.find(PostcardTemplate.class, uuid);
	}
}
